const Service = require('egg').Service;

class menu extends Service {
  //查询所有数据
  async findAll() {
    const post = await this.app.mysql.select('menu');
    //处理树形结构
    let menuTree = toTree(post);
    return menuTree;
  }
  //:id查询单条数据
  async findOne(id) {
    const post = await this.app.mysql.get('menu', { id: id });
    return post;
  }
  //创建菜单
  async create(val){
    let parentId = val.parentId;
    if(parentId === -1){
      const result = await this.app.mysql.insert('menu',{ type:val.type,name:val.name,icon:val.icon,path:val.path,component:val.component,redirect:val.redirect,parent_id:-1 });
      //判断插入成功
      const insertSuccess = result.affectedRows === 1;
      if(insertSuccess){
        return result;
      }
      return -1;
    }else{
      const load = await this.app.mysql.get('menu',{id:parentId});
      if(load){
        const result = await this.app.mysql.insert('menu',{ type:val.type,name:val.name,icon:val.icon,path:val.path,component:val.component,redirect:val.redirect,parent_id:parentId });
        //判断插入成功
        const insertSuccess = result.affectedRows === 1;
        if(insertSuccess){
          return result;
        }
        return -1;
      }else{
        return -1;
      }
    }
  }
  //更新菜单
  async update(val,params){
    console.log(params.id)
    let ComponentVal = null;
    if(val.type!==1){
      ComponentVal = val.component;
    }
    const data = {
      id:params.id,
      parent_id:val.parentId,
      type:val.type,
      name:val.name,
      icon:val.icon,
      path:val.path,
      component:ComponentVal,
      redirect:val.redirect,
    }
    const result = await this.app.mysql.update("menu",data);
    const updateSuccess = result.affectedRows === 1;
    if(updateSuccess){
      return result;
    }else{
      return -1;
    }
  }
  //删除菜单
  async destroy(id){
    console.log(id);
    const SelectRow = await this.app.mysql.get('menu',{id:id});
    if(SelectRow!==null){
      //删除本条数据
      const reasultId = await this.app.mysql.delete('menu',{id:id});
      //删除相关连的数据
      const reasultParId = await this.app.mysql.delete('menu',{parent_id:id});
      return reasultId;
    }else{
      return -1;
    }
  }
}

//树形结构方法
function toTree(data) {
  // 删除 所有 children,以防止多次调用
  data.forEach(function(item) {
    delete item.routes;
  });

  // 将数据存储为 以 id 为 KEY 的 map 索引数据列
  var map = {};
  data.forEach(function(item) {
    map[item.id] = item;
  });
  //        console.log(map);
  var val = [];
  data.forEach(function(item) {
    // 以当前遍历项，的pid,去map对象中找到索引的id
    var parent = map[item.parent_id];
    // 好绕啊，如果找到索引，那么说明此项不在顶级当中,那么需要把此项添加到，他对应的父级中
    if (parent) {
      (parent.routes || (parent.routes = [])).push(item);
    } else {
      //如果没有在map中找到对应的索引ID,那么直接把 当前的item添加到 val结果集中，作为顶级
      val.push(item);
    }
  });
  return val;
}
module.exports = menu;
